package vampire.com.baidumusic.aty.main;


import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import vampire.com.baidumusic.R;
import vampire.com.baidumusic.base.BaseActivity;
import vampire.com.baidumusic.fragment.MainFragment;
import vampire.com.baidumusic.fragment.player.PlayerBean;
import vampire.com.baidumusic.fragment.player.PlayerFragment;
import vampire.com.baidumusic.fragment.player.lyirc.LyricFragment;
import vampire.com.baidumusic.fragment.player.inside.PICFragment;
import vampire.com.baidumusic.service.PlayerService;
import vampire.com.baidumusic.tools.dbtools.DBMusicList;
import vampire.com.baidumusic.tools.dbtools.DBMyFavoriteList;
import vampire.com.baidumusic.tools.dbtools.DBMyMusicList;
import vampire.com.baidumusic.tools.dbtools.DBTool;
import vampire.com.baidumusic.tools.event.AskBottom;
import vampire.com.baidumusic.tools.event.AskPlayList;
import vampire.com.baidumusic.tools.event.AskState;
import vampire.com.baidumusic.tools.event.BottomInformationEvent;
import vampire.com.baidumusic.tools.event.CleanNotifycation;
import vampire.com.baidumusic.tools.event.IsSelected;
import vampire.com.baidumusic.tools.event.PlayMode;
import vampire.com.baidumusic.tools.event.PlayerBeanEvent;
import vampire.com.baidumusic.tools.event.PlayerStateEvent;
import vampire.com.baidumusic.tools.event.ProgressEvent;
import vampire.com.baidumusic.tools.event.RequestState;
import vampire.com.baidumusic.tools.event.SongIdEvent;
import vampire.com.baidumusic.values.KeyValues;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    private FragmentManager manager;
    private ImageView player; // 播放 暂停 开关
    private boolean state = true; // 播放开关状态 true为播放
    private List list;  // 歌曲列表集合
    private List song; // 歌名集合
    private List name; //歌手集合

    private TextView title; // 曲名
    private TextView author; // 歌手名
    private ImageView pic; // 底部图片
    private String songID;
    private PICFragment picFragment;
    private LyricFragment lyricFragment;
    private PlayerBean playerBean;
    private PlayerFragment playerFragment;
    private PopupWindow popupWindow;

    private LinearLayout linearLayout;
    private boolean playerState = false;

    private Button btnList;
    private List<DBMusicList> popBeen;
    private ImageView playState;

    private PopAdapter popAdapter;
    private AskState askState;

    public LinearLayout getLinearLayout() {
        return linearLayout;
    }

    private PlayerService.PlayerBinder playerBinder;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            playerBinder = (PlayerService.PlayerBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        EventBus.getDefault().post(new AskBottom());
    }


    @Subscribe
    public void getBean(PlayerBeanEvent playerBeanEvent) {
        playerBean = playerBeanEvent.getPlayerBean();
        author.setText(playerBean.getSonginfo().getAuthor());
        title.setText(playerBean.getSonginfo().getTitle());
        mNetTool.getImage(playerBean.getSonginfo().getPic_premium(), pic);

        picFragment = new PICFragment();
        lyricFragment = new LyricFragment();
        Bundle bundle = new Bundle();
        bundle.putString(KeyValues.PIC_HUGE, playerBean.getSonginfo().getPic_huge());
        picFragment.setArguments(bundle);

    }


    // 接收播放列表
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getPlayList(List<DBMusicList> dbMusicList) {
        Log.d("MainActivity", "get");
        popBeen = dbMusicList;
        popAdapter.setList(popBeen);

    }

    // 播放状态
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setPlayerState(SongIdEvent playerState) {
        player.setImageResource(R.mipmap.poss_icon);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getState(RequestState requestState) {
        Log.d("MainActivity", "requestState.isPlaying():" + requestState.isPlaying());
        if (requestState.isPlaying()) {
            player.setImageResource(R.mipmap.poss_icon);
        } else {
            player.setImageResource(R.mipmap.start_icon);
        }
    }

    // 播放模式
    @Subscribe
    public void getPlayMode(PlayMode playStateplayMode) {
        int playType = playStateplayMode.getPlayMode();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void bottomInformaition(BottomInformationEvent bottomInformationEvent) {

        title.setText(bottomInformationEvent.getSong());
        author.setText(bottomInformationEvent.getAuthor());
        mNetTool.getImage(bottomInformationEvent.getPic(), pic);

    }

    @Override
    protected int setLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        Intent playerService = new Intent(this, PlayerService.class);
        // 绑定服务 用于在activity中获取binder对象
        bindService(playerService, connection, BIND_AUTO_CREATE);

        PlayerStateEvent playerStateEvent = new PlayerStateEvent();
        EventBus.getDefault().post(playerStateEvent);

        linearLayout = bindView(R.id.linear_bottom_main);

        btnList = bindView(R.id.btn_list_main);
        player = bindView(R.id.btn_start_main);
        Button next = bindView(R.id.btn_next_main);

        title = bindView(R.id.text_title_main);
        author = bindView(R.id.text_player);
        pic = bindView(R.id.image_cd_main);

        linearLayout.setOnClickListener(this); // 底部状态栏
        btnList.setOnClickListener(this); // 歌单
        next.setOnClickListener(this);// 下一曲

        MainFragment mainFragment = new MainFragment();
        manager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = manager.beginTransaction();
        fragmentTransaction.add(R.id.main_frame_layout, mainFragment);
        fragmentTransaction.commit();

        playerFragment = new PlayerFragment();


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        CleanNotifycation cleanNotifycation = new CleanNotifycation();
//        EventBus.getDefault().post(cleanNotifycation);
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        BmobUser bmobUser = BmobUser.getCurrentUser();
        // 拉取 我最喜欢的单曲
        BmobQuery<DBMyMusicList> dbMyMusicListBmobQuery = new BmobQuery<DBMyMusicList>();
        dbMyMusicListBmobQuery.addWhereEqualTo("username", bmobUser.getUsername());
        // 返回数据条数 默认10条
        dbMyMusicListBmobQuery.setLimit(99999);
        // 执行查询方法
        dbMyMusicListBmobQuery.findObjects(new FindListener<DBMyMusicList>() {
            @Override
            public void done(List<DBMyMusicList> list, BmobException e) {
                if (e == null) {
                    for (DBMyMusicList dbMyMusicList : list) {
                        DBTool.getInstance().instertMyDBMusicList(dbMyMusicList, 0);
                    }
                } else {
                    Log.d("SignInActivity", "拉取 我最喜欢的单曲 失败: " + e.getMessage() + "," + e.getErrorCode());
                }
            }
        });

        // 拉取 我喜欢的歌单
        BmobQuery<DBMyFavoriteList> dbMyFavoriteListBmobQuery = new BmobQuery<DBMyFavoriteList>();
        dbMyFavoriteListBmobQuery.addWhereEqualTo("username", bmobUser.getUsername());
        dbMyFavoriteListBmobQuery.setLimit(999999);
        dbMyFavoriteListBmobQuery.findObjects(new FindListener<DBMyFavoriteList>() {
            @Override
            public void done(List<DBMyFavoriteList> list, BmobException e) {
                if (e == null) {
                    for (DBMyFavoriteList dbMyFavoriteList : list) {
                        DBTool.getInstance().insertMyFavoriteList(dbMyFavoriteList, 0);
                        Log.d("SignInActivity", "done");
                    }
                } else {
                    Log.d("SignInActivity", "拉取 我喜欢的歌单 失败: " + e.getMessage() + "," + e.getErrorCode());
                }
            }
        });

    }

    @Override
    protected void initData() {
        askState = new AskState();
        // 播放状态按钮
        player.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                EventBus.getDefault().post(askState);
            }
        });

    }

    // 点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.linear_bottom_main: // 底部播放栏
                if (playerBean != null) {
                    updateView(playerFragment);
                    linearLayout.setVisibility(View.GONE);
                } else {

                }

                break;
            case R.id.btn_list_main: // popUpWindow;
                AskPlayList askPlayList = new AskPlayList();
                EventBus.getDefault().post(askPlayList);
                showPopupWindow();
                break;
            case R.id.btn_next_main: // 下一曲
                playerBinder.playerNext();
                break;
        }

    }

    // 替换fragment
    public void updateView(Fragment newFragment) {

        FragmentTransaction transaction = manager.beginTransaction();
        transaction.add(R.id.main_frame_layout, newFragment, "" + newFragment).addToBackStack(null).commit();

    }

    // 获取binder
    public PlayerService.PlayerBinder getPlayerBinder() {
        return playerBinder;
    }

    public LyricFragment getLyricFragment() {
        return lyricFragment;
    }

    public PICFragment getPicFragment() {
        return picFragment;
    }

    // 弹出PopupWindow
    private void showPopupWindow() {

        View contentView = LayoutInflater.from(MainActivity.this).inflate(R.layout.popup_windos, null);

        popupWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, 700, true);

        popupWindow.setContentView(contentView);

        playState = (ImageView) contentView.findViewById(R.id.pop_play_mode);

        int mode = playerBinder.getPlayMode();
        switch (mode) {
            case 0: // normal
                playState.setImageResource(R.mipmap.normal);
                break;
            case 1: // 单曲
                playState.setImageResource(R.mipmap.one);
                break;
            case 2://随机
                playState.setImageResource(R.mipmap.random);
                break;
        }
        playState.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int mode = playerBinder.changeMode();
                switch (mode) {
                    case 0: // normal
                        playState.setImageResource(R.mipmap.normal);
                        break;
                    case 1: // 单曲
                        playState.setImageResource(R.mipmap.one);
                        break;
                    case 2://随机
                        playState.setImageResource(R.mipmap.random);
                        break;
                }
            }
        });


        ListView listView = (ListView) contentView.findViewById(R.id.lv_popupwindos);
        popAdapter = new PopAdapter(this);
        popAdapter.setList(popBeen);
        listView.setAdapter(popAdapter);


        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                playerBinder.playerMusic(position);
                popupWindow.dismiss();
            }
        });


        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);

    }

    // 进度条
    public void playerSeekTo(int progress) {
        playerBinder.seekTo(progress);
    }


}
